# @FileName  : tool.py
# @Time      : 2021/7/14 0014  18:15
# @Author    : LuZhaoHui
# @Software  : PyCharm

from os import environ

environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'

from configparser import ConfigParser

from PyQt5.QtCore import *
import sys
import os
import xlsxwriter, openpyxl
import json
import csv, codecs
import hashlib
import datetime

# import locale, re
# import inspect, ctypes, ast
# import threading, pygame
# import numpy, natsort
# import sys, paramiko, , uuid
# from mutagen.mp3 import MP3

EXE_PATH = os.path.abspath(os.getcwd())
BASE_PATH = os.path.dirname(EXE_PATH)
LOG_PATH = os.path.join(BASE_PATH, 'log').replace('\\', '/')


def deleteFile(name):
    if os.path.exists(name):
        os.remove(name)


def getListDir(dirs):
    # msg = eval(dirs)
    msg = dirs.split(',')
    if isinstance(msg, str):
        if os.path.exists(msg):
            return msg
    else:
        for s in msg:
            if os.path.exists(s):
                return s
        return ''


def getPath1(path):
    return os.path.dirname(os.path.dirname(path))


def getPath2(path):
    return os.path.dirname(getPath1(path))


def format_number(amount):
    zheng = str(amount)
    res = []
    while True:
        if len(zheng) > 3:
            str1 = zheng[-3:]
            zheng = zheng[0:len(zheng) - 3]
            res.insert(0, str1)
        else:
            res.insert(0, zheng)
            break
    result = ','.join(res)
    return result


def getSizeByteToKb(byte):
    return int((byte + 512) / 1024)


def getPixToW(pix):
    return int((pix + 5000) / 10000)


def getStepToRangeMm(step):
    return (step / 1000 * 20.0)


def getRangeMmToStep(mm):
    return int(mm * 1000 / 20.0)


def pathJoin(path1, path2):
    return os.path.join(path1, path2).replace('\\', '/')


def listFind(list, item):
    try:
        index = list.index(item)
    except ValueError:
        index = -1
    return index


def trimList(list):
    index = [i for i, x in enumerate(list) if x == '' or x == ' ']
    for i in index[::-1]:
        del list[i]
    return list


def removeLast(text):
    return text[:text[:-1].rindex('\n') - len(text)]


def strRight(str, slen):
    s = str
    if len(str) > slen:
        s = '...' + str[(len(str) - slen):]
    return s


def curFunc(err):
    return '%s:%s' % (sys._getframe().f_code.co_name, str(err))


def writeXlsx(name, data):
    try:
        write = xlsxwriter.Workbook(name)
        sheet = write.add_worksheet()
        for i, cols in enumerate(data):
            for j, d in enumerate(cols):
                if isinstance(d, list):
                    l = len(d)
                    for k, dd in enumerate(d):
                        sheet.write(i, j * l + k, dd)
                else:
                    sheet.write(i, j, d)
        write.close()
    except Exception as e:
        print(curFunc(e))


def writeCsv(name, data):
    try:
        file_csv = codecs.open(name, 'w+', 'utf-8')
        writer = csv.writer(file_csv, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        for d in data:
            writer.writerow(d)
    except Exception as e:
        print(curFunc(e))


def addCsv(name, data):
    try:
        file_csv = codecs.open(name, 'a', 'utf-8')
        writer = csv.writer(file_csv, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        for d in data:
            writer.writerow(d)
    except Exception as e:
        print(curFunc(e))


def readXlsx(name):
    data = []
    if os.path.exists(name):
        read = openpyxl.load_workbook(name)
        sheets = read.get_sheet_names()
        sheet = read.get_sheet_by_name(sheets[0])
        rows = sheet.rows
        for row in rows:
            line = [col.value for col in row]
            data.append(line)
    return data


def readCsv(name, type=[]):
    data = []
    if os.path.exists(name):
        if os.path.exists(name):
            with open(name, encoding='utf-8') as csvfile:
                csv_reader = csv.reader(csvfile)
                cmd = 'data.append(row)'
                if len(type) > 0:
                    cmd = 'data.append(['
                    for i, t in enumerate(type):
                        if t == 'int':
                            cmd += 'int(row[%d]),' % (i)
                            continue
                        if t == 'float':
                            cmd += 'float(row[%d]),' % (i)
                            continue
                        cmd += 'row[%d],' % (i)
                    cmd = cmd[:-1] + '])'
                for row in csv_reader:
                    exec(cmd)
                    # data.append(row)
    return data


def retDirList(path):
    dirs = []
    if os.path.exists(path):
        for f in sorted(os.listdir(path)):
            if os.path.isdir(pathJoin(path, f)):
                dirs.append(f)
    return dirs


def GetFileByte(file):
    info = QFileInfo(file)
    byte = info.size()
    return byte


def GetFileByteModify(file):
    info = QFileInfo(file)
    byte = info.size()
    modify = info.lastModified()
    return byte, modify


def GetFileMd5(file):
    md5 = ''
    size = 64 * 1024
    if os.path.isfile(file):
        with open(file, 'rb') as f:
            md5_obj = hashlib.md5()
            while True:
                d = f.read(size)
                if not d:
                    break
                md5_obj.update(d)
            hash_code = md5_obj.hexdigest()
            md5 = str(hash_code).lower()
    return md5


def GetFileEncrypt(file, type='sha1'):
    sha = ''
    if os.path.isfile(file):
        with open(file, 'rb') as f:
            hash_code = hashlib.new(type, f.read()).hexdigest()
            sha = str(hash_code).lower()
    return sha


class MyParser(ConfigParser):
    "Inherit from built-in class: ConfigParser"

    def optionxform(self, optionstr):
        "Rewrite without lower()"
        return optionstr


def nowDateTime():
    return datetime.datetime.now()


def dateTimeStr(dtStr):
    return datetime.datetime.strptime(dtStr, '%Y-%m-%d %H:%M:%S')


def nowDateTime0():
    return datetime.datetime.combine(datetime.datetime.now(), datetime.time(0, 0, 0))


def nowDateTimeStr():
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')


def nowDateTimeInt():
    return int(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))


def nowDateStr():
    return datetime.datetime.now().strftime('%Y-%m-%d')


def nowTimeStr():
    return datetime.datetime.now().strftime('%H:%M:%S')


def dateToInt(date):
    return int(date.toString('yyyyMMdd'))


def dateStrToFmt(dateStr):
    return '%s-%s-%s' % (dateStr[:4], dateStr[4:6], dateStr[-2:])


def timeStrToFmt(timeStr):
    return '%s:%s:%s' % (timeStr[:2], timeStr[2:4], timeStr[-2:])


def readJson(log=''):
    if len(log) == 0:
        file = LOG_PATH + '/json.json'
    else:
        file = LOG_PATH + '/' + log + '.json'
    with open(file, 'r', encoding='utf-8') as f:
        json_str = f.read()
        f.close()
    dict = json.loads(json_str)
    return dict


def saveJson(dict, log=''):
    if not os.path.exists(LOG_PATH):
        os.mkdir(LOG_PATH)
    if len(log) == 0:
        file = LOG_PATH + '/json.json'
    else:
        file = LOG_PATH + '/' + log + '.json'
    json_str = ''
    try:
        with open(file, 'w', encoding='utf-8') as f:
            json_str = json.dumps(dict, ensure_ascii=False)
            f.write(json_str)
    except Exception as e:
        print(e)
    return json_str


def saveLog(msg, log=''):
    if not os.path.exists(LOG_PATH):
        os.mkdir(LOG_PATH)
    if len(log) == 0:
        file = LOG_PATH + '/' + nowDateStr() + '.log'
    else:
        if len(os.path.splitext(log)) > 1:
            file = LOG_PATH + '/' + log
        else:
            file = LOG_PATH + '/' + log + '-' + nowDateStr() + '.log'
    logStr = ''
    try:
        with open(file, 'a', encoding='utf-8') as f:
            logStr = nowTimeStr() + ' ' + msg + '\n'
            f.write(logStr)
    except Exception as e:
        print(e)
    return logStr
